package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-12
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> login(AdUserLoginDto dto) {
        //1、参数校验
        if(dto==null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、基于用户名查询用户信息
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(dto.getName())){
            queryWrapper.lambda().eq(AdUser::getName,dto.getName());
        }
        AdUser adUser = getOne(queryWrapper);
        if (adUser==null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"用户名错误");
        }
        //3、比较密码是否正确
        boolean matches = passwordEncoder.matches(dto.getPassword(), adUser.getPassword());
        if(!matches){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
        }
        //4、基于Jwt工具类生成token
        String token = JwtUtils.generateTokenExpireInSeconds(adUser.getId(), 3600);
        //5、组装map集合数据
        Map<String,Object> map = new HashMap<>();
        adUser.setPassword("");
        adUser.setEmail("");
        map.put("user",adUser);
        map.put("token",token);
        return map;
    }
}
